﻿#include "Map.h"
#include "Spell.h"
#include "Item.h"
#include "SimpleAudioEngine.h"
#include "GetString.h"
#pragma execution_character_set("utf-8")

static Map_Layer* _Map_Layer = nullptr;
static Map_Scene* _Map_Scene = nullptr;
static PlayerUILayer* _PlayerUIInstance = nullptr;

Scene* Map_Scene::createScene()
{
	// 'scene' is an autorelease object
	auto scene = Scene::create();

	// 'layer' is an autorelease object
	auto layer = Map_Scene::create();
	// add layer as a child to scene
	scene->addChild(layer);
	// return the scene
	return scene;
}

Map_Scene* Map_Scene::GetInstance()
{
	if (_Map_Scene == nullptr)
	{
		return nullptr;
	}
	return _Map_Scene;
}

Map_Scene::Map_Scene()
{
	_Map_Layer = NULL;
	_PlayerUILayer = NULL;
	VisableSize = CCDirector::sharedDirector()->getVisibleSize();
	UISize = VisableSize.width / 1280;
	DeadPunish_Money	= 0;
	DeadPunish_Exp		= 0;
	m_NowMapID			= 2;
}

Map_Scene::~Map_Scene()
{

}

bool Map_Scene::init()
{
	bool bRef = false;
	do
	{
		CC_BREAK_IF(!CCScene::init());
		std::thread th(&Map_Scene::LoadEveryThingFromDB, this);
		th.join();
		_Map_Scene = this;

		_player = new Player();
		//player->setPosition(VisableSize.width / 2, VisableSize.height / 2);
		_player->setTag(999999);

		_PlayerUILayer = PlayerUILayer::create();
		CC_BREAK_IF(!_PlayerUILayer);
		_PlayerUILayer->setTag(9000);

		_Map_Layer = Map_Layer::create();
		_Map_Layer->setTag(100);
		
		CC_BREAK_IF(!_Map_Layer);
		addChild(_Map_Layer);
		addChild(_PlayerUILayer);
		LoadConfDefault();
		scheduleUpdate();
		CocosDenshion::SimpleAudioEngine::getInstance()->sharedEngine()->stopBackgroundMusic();

		bRef = true;

	} while (0);

	return bRef;
}

void Map_Scene::LoadConfDefault()
{
	DeadPunish_Money		= atoi(sConfig->GetStringForKey("PlayerDead_Money"));
	DeadPunish_Exp			= atoi(sConfig->GetStringForKey("PlayerDead_Exp"));
	DeadPunish_Exp = DeadPunish_Exp / 100;
}

int Map_Scene::GetNowMapID()
{
	return m_NowMapID;
}

void Map_Scene::LoadEveryThingFromDB()
{
	LoadLevelTemplate();
	LoadMapMonsterInfo();
	LoadMapInfo();
	LoadItemTemplate();
	LoadLootTemplate();
}

ItemTemplateStr Map_Scene::GetItemTemplate(int _Entry)
{ 
	ItemTemplateStr _ItemTemplateStr;
	_ItemTemplateStr.Entry = 0;
	if (ItemTemplate.find(_Entry) != ItemTemplate.end())
		_ItemTemplateStr = ItemTemplate[_Entry];
	return _ItemTemplateStr;
}

void Map_Scene::LoadLootTemplate()
{
	MonsterLootMap.clear();
	//																				   0	 1	  2		3		4
	Result::Qurey result = Database::GetInstance()->GetResult(WorldDatabase, "SELECT Entry,Item,Count,MaxCount,Chance FROM monster_loot_template");

	if (result.empty())
	{
		log("Loot Template Empty!");
	}
	else
	{
		int TempEntry = -99;
		for (Result::Qurey::iterator itr = result.begin(); itr != result.end(); itr++)
		{
			std::vector<MonsterLootSingleInfo> TempVector;
			bool IsNewOrder;
			TempEntry == atoi(itr->second.at(0).c_str()) ? IsNewOrder = false : IsNewOrder = true;
			MonsterLootSingleInfo _MonsterLootSingleInfo;
			_MonsterLootSingleInfo.MonsterEntry						= atoi(itr->second.at(0).c_str());
			_MonsterLootSingleInfo.Item_Entry						= atoi(itr->second.at(1).c_str());
			_MonsterLootSingleInfo.Count							= atoi(itr->second.at(2).c_str());
			_MonsterLootSingleInfo.MaxCount							= atoi(itr->second.at(3).c_str());
			_MonsterLootSingleInfo.Chance							= atoi(itr->second.at(4).c_str());
			TempVector.push_back(_MonsterLootSingleInfo);
			if (IsNewOrder)
			{
				MonsterLootMap[_MonsterLootSingleInfo.MonsterEntry] = TempVector;
			}
			else
			{
				MonsterLootMap[_MonsterLootSingleInfo.MonsterEntry].push_back(_MonsterLootSingleInfo);
			}
			TempEntry = _MonsterLootSingleInfo.MonsterEntry;
		}
	}
}

std::vector<MonsterLootSingleInfo> Map_Scene::GetLootTemplate(int MonesterEntry)
{
	std::vector<MonsterLootSingleInfo> _tempvector;
	if (MonsterLootMap.find(MonesterEntry) != MonsterLootMap.end())
		_tempvector = MonsterLootMap[MonesterEntry];
	return _tempvector;
}

void Map_Scene::LoadItemTemplate()
{
	ItemTemplate.clear();
	char valuetext[255], valuenumber[255];
	//							0	 1		2			3		4			5		6				7
	std::string msg = "SELECT Entry,Name,Image_Url,NeedLevel,SellPrice,BuyPrice,Exchange_Cost,Item_Flag,Item_Slot,Item_Class";
	for (size_t i = 1; i != MAX_ITEM_VALUE_COUNT + 1; i++)
	{
		snprintf(valuetext, 255, ",Value_%d,", i);
		snprintf(valuenumber, 255, "Value_Number_%d", i);
		msg += valuetext;
		msg += valuenumber;
	}
	msg += " FROM Item_Template;";
	Result::Qurey result = Database::GetInstance()->GetResult(WorldDatabase, msg.c_str());
	if (result.empty())
		log("Empty ItemTemplate Result!");
	else
	{
		for (Result::Qurey::iterator itr = result.begin(); itr != result.end(); itr++)
		{
			ItemTemplateStr _ItemTemplateStr;
			_ItemTemplateStr.Entry						= atoi(itr->second.at(0).c_str());
			_ItemTemplateStr.Name						= itr->second.at(1).c_str();
			_ItemTemplateStr.Image_Url					= itr->second.at(2).c_str();
			_ItemTemplateStr.NeedLevel					= atoi(itr->second.at(3).c_str());
			_ItemTemplateStr.SellPrice					= atoi(itr->second.at(4).c_str());
			_ItemTemplateStr.BuyPrice					= atoi(itr->second.at(5).c_str());
			_ItemTemplateStr.Exchange_Cost				= atoi(itr->second.at(6).c_str());
			_ItemTemplateStr.Item_Flag					= atoi(itr->second.at(7).c_str());
			_ItemTemplateStr.Item_Slot					= (ItemSlot)atoi(itr->second.at(8).c_str());
			_ItemTemplateStr.NeedClass					= (ClassID)atoi(itr->second.at(9).c_str());
			_ItemTemplateStr.BondingType				= (BondingType)atoi(itr->second.at(10).c_str());
			for (int i = 10; i != 32; i++)
			{
				if (!atoi(itr->second.at(i).c_str()))
				{
					i++;
					continue;
				}
				else
				{
					_ItemTemplateStr.ItemValues[(ItemValue)atoi(itr->second.at(i).c_str())] = atoi(itr->second.at(i + 1).c_str());
					i++;
				}
			}
			ItemTemplate[_ItemTemplateStr.Entry] = _ItemTemplateStr;
		}
	}
}

void Map_Scene::LoadMapInfo()
{
	MapMonsterVector.clear();
	MapInfoMap.clear();
	char msg[255];
	for (int mapid = 1; mapid != MAPID_MAX; mapid++)
	{
		//							0		1	2	3	  4
		snprintf(msg, 255, "SELECT mapid,entry,guid,posx,posy FROM map_monster_info WHERE mapid = %u", mapid);
		Result::Qurey result = Database::GetInstance()->GetResult(WorldDatabase, msg);
		if (result.empty())
		{
			break;
		}
		else
		{
			for (Result::Qurey::iterator itr = result.begin(); itr != result.end(); itr++)
			{
				MapInfo _MapInfo;
				_MapInfo.MapID								= atoi(itr->second.at(0).c_str());
				_MapInfo.MonsterEntry						= atoi(itr->second.at(1).c_str());
				_MapInfo.MonsterGuid						= atoi(itr->second.at(2).c_str());
				_MapInfo.PosX								= atoi(itr->second.at(3).c_str());
				_MapInfo.PosY								= atoi(itr->second.at(4).c_str());
				MapMonsterVector.push_back(_MapInfo);
			}
			MapInfoMap[mapid]								= MapMonsterVector;
			MapMonsterVector.clear();
		}
	}
}

void Map_Scene::LoadLevelTemplate()
{
	LevelInfoVector.clear();
																				//		0	1
	Result::Qurey result = Database::GetInstance()->GetResult(WorldDatabase, "SELECT level,need_exp FROM level_template");
	if (!result.empty())
	{
		for (Result::Qurey::iterator itr = result.begin(); itr != result.end(); itr++)
		{
			LevelInfo _Info;
			_Info.Level			= atoi(itr->second.at(0).c_str());
			_Info.NeedExp		= atoi(itr->second.at(1).c_str());
			LevelInfoVector.push_back(_Info);
		}
	}
	else
	{
		log("Level_Template Is Empty!");
	}
}

void Map_Scene::LoadMapMonsterInfo()
{

	MonsterMap.clear();
	//																					0		1		2			3		4			5			6	7		8		9				10
	Result::Qurey result = Database::GetInstance()->GetResult(WorldDatabase, "SELECT entry,maxheath,attack_power,defance,miss_chance,crit_chance,level,loot,imageurl,deadsoundurl,takedamagesoundurl,rewardexp,rewardmoney FROM creature");
	if (!result.empty())
	{
		for (Result::Qurey::iterator itr = result.begin(); itr != result.end(); itr++)
		{
			MonstersBaseInfo _MonstersBaseInfo;
			_MonstersBaseInfo.Entry					= atoi(itr->second.at(0).c_str());
			_MonstersBaseInfo.maxheath				= atoi(itr->second.at(1).c_str());
			_MonstersBaseInfo.Attack_Power			= atoi(itr->second.at(2).c_str());
			_MonstersBaseInfo.Defance				= atoi(itr->second.at(3).c_str());
			_MonstersBaseInfo.MissChance			= atoi(itr->second.at(4).c_str());
			_MonstersBaseInfo.CritChance			= atoi(itr->second.at(5).c_str());
			_MonstersBaseInfo.Level					= atoi(itr->second.at(6).c_str());
			_MonstersBaseInfo.Loot					= atoi(itr->second.at(7).c_str());
			_MonstersBaseInfo.imageurl				= itr->second.at(8).c_str();
			_MonstersBaseInfo.deadsoundurl			= itr->second.at(9).c_str();
			_MonstersBaseInfo.takedamagesoundurl	= itr->second.at(10).c_str();
			_MonstersBaseInfo.reswardexp			= atoi(itr->second.at(11).c_str());
			_MonstersBaseInfo.rewardmoney			= atoi(itr->second.at(12).c_str());
			MonsterMap[_MonstersBaseInfo.Entry]		= _MonstersBaseInfo;
		}
	}
}

void Map_Scene::update(float diff)
{
	
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////UI_LAYER///////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
PlayerUILayer::PlayerUILayer()
{
	m_IsTouchWithItem = false;
	_PlayerUIInstance = this;
	_TouchedSprite = nullptr;
	m_TouchedItem = nullptr;
	ButtonMainUI = nullptr;
	ButtonSkillKeyBoardUI = nullptr;
	PlayerDeadTalkClass = nullptr;
	PlayerValueUILable.clear();
	TouchedUI = -1;
	TouchMoveX = 0;
	TouchMoveY = 0;
	LastTouchX = 0;
	LastTouchY = 0;
	m_MouseMoveToTag = MOUSE_SELECTED_NONE;
}

PlayerUILayer::~PlayerUILayer()
{

}

PlayerUILayer* PlayerUILayer::GetInstance()
{
	if (_PlayerUIInstance == nullptr)
	{
		_PlayerUIInstance = new PlayerUILayer();
	}
	return _PlayerUIInstance;
}

void PlayerUILayer::ResetLevelString()
{
	std::string leveltext = "LV.";
	leveltext += itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetLevel()).c_str();
	LevelText->setString(leveltext);
}

bool PlayerUILayer::init()
{
	bool bRef = false;
	do
	{
		CC_BREAK_IF(!CCLayer::init());
		auto listener = EventListenerTouchOneByOne::create();
		InitPlayerEquipUI();
		InitButtonMainUI();
		InitCharacterValueUI();
		InitPlayerDeadTalkClass();
		listener->setSwallowTouches(true);
		listener->onTouchBegan = CC_CALLBACK_2(PlayerUILayer::onTouchBegan, this);
		listener->onTouchMoved = CC_CALLBACK_2(PlayerUILayer::onTouchMoved, this);
		listener->onTouchEnded = CC_CALLBACK_2(PlayerUILayer::onTouchEnded, this);
		_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);


		auto _mouseListener = EventListenerMouse::create();
		_mouseListener->onMouseMove = CC_CALLBACK_1(PlayerUILayer::onMouseMove, this);
		//_mouseListener->onMouseUp = CC_CALLBACK_2(PlayerUILayer::onMouseUp, this);
		//_mouseListener->onMouseDown = CC_CALLBACK_2(PlayerUILayer::onMouseDown, this);
		//_mouseListener->onMouseScroll = CC_CALLBACK_2(PlayerUILayer::onMouseScroll, this);

		_eventDispatcher->addEventListenerWithSceneGraphPriority(_mouseListener, this);

		scheduleUpdate();
		bRef = true;
	} while (0);

	return bRef;
}

void PlayerUILayer::InitPlayerDeadTalkClass()
{
	PlayerDeadTalkClass = CCSprite::create("ui/TalkClass/DeadTalkClass.png");
	PlayerDeadTalkClass->setPosition(VisableSize.width / 2, VisableSize.height / 2);
	PlayerDeadTalkClass->setTag(PLAYER_DEAD_TALK_CLASS_TAG);
	PlayerDeadTalkClassButton = CCSprite::create("ui/TalkClass/Ok_Normal.png");
	PlayerDeadTalkClassButton->setPosition(PlayerDeadTalkClass->getContentSize().width / 2, PlayerDeadTalkClass->getContentSize().height * 0.415f);
	PlayerDeadTalkClassButton->setTag(PLAYER_DEAD_TALK_CLASS_BUTTON_TAG);
	PlayerDeadTalkClass->addChild(PlayerDeadTalkClassButton);
	PlayerDeadTalkClass->setVisible(false);
	PlayerDeadTalkClass->setOpacity(255.0f * 0.8f);
	addChild(PlayerDeadTalkClass);
}

void PlayerUILayer::onMouseMove(Event *event)
{
	//bool SelectedCurSprite = false;
	if (EventMouse* pMouse = (EventMouse*)event)
	{
		float x = pMouse->getCursorX();
		float y = pMouse->getCursorY();
		Vec2 touchLocation = pMouse->getLocation();
		touchLocation.x = x;
		touchLocation.y = y;
		Bag* PlayerBag = Map_Scene::GetInstance()->GetLoadedPlayer()->GetBag();
		if (PlayerBag->isVisible())
		{
			int pSlot = PlayerBag->GetTouchedSlot(touchLocation);
			if (pSlot >= BAG_SLOT_TAG_BEGIN && pSlot <= BAG_SLOT_TAG_ENDED)
			{
				if (Slot* TempSlot = PlayerBag->GetSlot(pSlot))
				{
					SetMouseMoveToTag(TempSlot->getTag());
					return;
				}
			}
		}
		else if (_EquipUI->isVisible())
		{
			int pSlot = _EquipUI->GetTouchedSlot(touchLocation);
			if (pSlot >= PLAYER_EQUIP_SLOT_START && pSlot <= PLAYER_EQUIP_SLOT_END)
			if (Slot* TempSlot = _EquipUI->GetSlot(pSlot))
			{
				SetMouseMoveToTag(TempSlot->getTag());
				return;
			}
		}
	}
	//if (!SelectedCurSprite)
		SetMouseMoveToTag(MOUSE_SELECTED_NONE);
}
void PlayerUILayer::SetMouseMoveToTag(int _Tag)			
{
	if (_Tag != m_MouseMoveToTag)
	{
		m_MouseMoveToTag = _Tag;
		m_MouseMoveFlag = FLAG_CHANGEED;
	}
}

void PlayerUILayer::InitPlayerEquipUI()
{
	_EquipUI = new EquipUI();
	_EquipUI->setPosition(Director::sharedDirector()->getVisibleSize().width / 2, Director::sharedDirector()->getVisibleSize().height / 2);
	_EquipUI->setTag(PLAYER_EQUIP_UI_TAG);
	_EquipUI->setVisible(false);
	Map_Scene::GetInstance()->GetLoadedPlayer()->SetEquipBag(_EquipUI);
	_EquipUI->LoadSlotFromDB();
	addChild(_EquipUI);
}

CCLabelTTF* PlayerUILayer::GetPlayerValuesLable(PlayerValuesViewName _PlayerValuesViewName)
{
	if (PlayerValueUILable.find(_PlayerValuesViewName) == PlayerValueUILable.end())
	{
		return nullptr;
	}
	return PlayerValueUILable[_PlayerValuesViewName];
}

void PlayerUILayer::InitCharacterValueUI()
{
	CharacterValue_Main_UI = CCSprite::create("ui/CharacterValues_Main.png");
	CharacterValue_Main_UI_Back = CCSprite::create("ui/CharacterBack_Main.png");
	CharacterValue_Main_UI->setPosition(CharacterValue_Main_UI_Back->getContentSize().width / 2 + 0.5f, CharacterValue_Main_UI_Back->getContentSize().height / 2 - CharacterValue_Main_UI_Back->getBoundingBox().size.height * 0.02);
	CharacterValue_Main_UI_Back->addChild(CharacterValue_Main_UI);
	CharacterValue_Main_UI_Back->setPosition(Director::sharedDirector()->getVisibleSize().width / 2, Director::sharedDirector()->getVisibleSize().height / 2);
	CharacterValue_Main_UI_Back->setOpacity(255 * 0.7f);
	CharacterValue_Main_UI->setOpacity(255);
	addChild(CharacterValue_Main_UI_Back);
	CharacterValue_Main_UI_Back->setTag(CHARACTER_VALUE_BACK_TAG);
	CharacterValue_Main_UI->setTag(CHARACTER_VALUE_TAG);

	CharacterValue_Detail_UI = CCSprite::create("ui/CharacterDetails_Main.png");
	CharacterValue_Detail_UI_Back = CCSprite::create("ui/CharacterBack_Detail.png");
	CharacterValue_Detail_UI->setPosition(CharacterValue_Detail_UI_Back->getContentSize().width / 2 + 0.5f, CharacterValue_Detail_UI_Back->getContentSize().height / 2);
	CharacterValue_Detail_UI_Back->addChild(CharacterValue_Detail_UI);
	CharacterValue_Detail_UI_Back->setTag(CHARACTER_VALUE_DETAIL_BACK_TAG);
	CharacterValue_Detail_UI->setTag(CHARACTER_VALUE_DETAIL_TAG);
	CharacterValue_Detail_UI_Back->setOpacity(255 * 0.7f);
	CharacterValue_Detail_UI->setOpacity(255);
	CharacterValue_Detail_UI_Back->setPosition(CharacterValue_Main_UI_Back->getBoundingBox().origin.x + CharacterValue_Main_UI_Back->getBoundingBox().size.width + CharacterValue_Detail_UI_Back->getBoundingBox().size.width / 2, CharacterValue_Main_UI_Back->getBoundingBox().origin.y + (CharacterValue_Detail_UI_Back->getBoundingBox().size.height / 2));
	addChild(CharacterValue_Detail_UI_Back);

	CharacterValue_Main_UI_Back->setVisible(false);
	CharacterValue_Detail_UI_Back->setVisible(false);

	//人数数据待添加
	for (int i = PLAYER_NAME; i != PLAYER_VALUE_VIEW_NAME_END; i++)
	{
		CCLabelTTF* TempLable = new CCLabelTTF();
		TempLable->initWithString("test", "Airal", 13, Size::ZERO, TextHAlignment::RIGHT, TextVAlignment::CENTER);
		TempLable->autorelease();
		TempLable->setColor(ccc3(0, 0, 0));
		PlayerValueUILable[(PlayerValuesViewName)i] = TempLable;
		float SinglePlus = TempLable->getBoundingBox().size.height + 5;
		if (i <= PLAYER_POP)
		{
			TempLable->setPosition(CharacterValue_Main_UI->getBoundingBox().size.width * 0.3773f, CharacterValue_Main_UI->getBoundingBox().size.height * 0.959f - (i * SinglePlus));
		}
		else if (i == PLAYER_UNUSED_TALENT)
		{
			TempLable->setPosition(CharacterValue_Main_UI->getBoundingBox().size.width * 0.434f, CharacterValue_Main_UI->getBoundingBox().size.height * 0.3858f);
		}
		else if (i <= PLAYER_LUK)
		{
			TempLable->setPosition(CharacterValue_Main_UI->getBoundingBox().size.width * 0.3773f, CharacterValue_Main_UI->getContentSize().height * 0.302f - ((i - 10) * SinglePlus));
		}
		else
		{
			if (i <= PLAYER_BP)
			{
				TempLable->setPosition(CharacterValue_Detail_UI->getBoundingBox().size.width * 0.47f, CharacterValue_Detail_UI->getContentSize().height * 0.9496f - ((i - 14) * SinglePlus));
			}
			else
			{
				TempLable->setPosition(CharacterValue_Detail_UI->getBoundingBox().size.width * 0.47f, CharacterValue_Detail_UI->getContentSize().height * 0.783f - ((i - 16) * SinglePlus));
			}
			CharacterValue_Detail_UI->addChild(TempLable);
			continue;
		}
		CharacterValue_Main_UI->addChild(TempLable);
	}

	ReLoadPlayerValueNumber();
}

void PlayerUILayer::ReLoadPlayerValueNumber()
{
	//待重构位置
	for (int i = PLAYER_NAME; i != PLAYER_VALUE_VIEW_NAME_END; i++)
	{
		if (CCLabelTTF* TempLable = GetPlayerValuesLable(PlayerValuesViewName(i)))
		{
			switch (i)
			{
			case PLAYER_NAME:
				TempLable->setString(Map_Scene::GetInstance()->GetLoadedPlayer()->GetName().c_str());
				break;
			case PLAYER_CLASS:
				TempLable->setString(Map_Scene::GetInstance()->GetLoadedPlayer()->GetClassString().c_str());
				break;
			case PLAYER_LEVEL:
				TempLable->setString(itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetLevel()).c_str());
				break;
			case PLAYER_PK:
				break;
			case PLAYER_FAMLIY:
				break;
			case PLAYER_HP:
			{
				std::string temp = itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetInt32Value(VALUE_HP)).c_str();
				temp += " / ";
				temp += itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_Heath)).c_str();
				TempLable->setString(temp.c_str());
				break;
			}
			case PLAYER_MP:
			{
				std::string temp = itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetInt32Value(VALUE_MP)).c_str();
				temp += " / ";
				temp += itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_Mana)).c_str();
				TempLable->setString(temp.c_str());
				break;
			}
			case PLAYER_REP:
				break;
			case PLAYER_POP:
				break;
			case PLAYER_UNUSED_TALENT:
				TempLable->setString(itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetInt32Value(UNUSE_TALENT)).c_str());
				break;
			case PLAYER_STR:
				TempLable->setString(itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_Str)).c_str());
				break;
			case PLAYER_DEX:
				TempLable->setString(itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_Dex)).c_str());
				break;
			case PLAYER_INT:
				TempLable->setString(itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_Int)).c_str());
				break;
			case PLAYER_LUK:
				TempLable->setString(itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_Luk)).c_str());
				break;
			case PLAYER_COMBAT_EXP:
				break;
			case PLAYER_BP:
				break;
			case PLAYER_ATTACK:
			{
				//待填充攻击力计算公式
				int Max = Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_Att);
				int Min = Max * 0.8;
				std::string text = itoc(Max);
				text += " - ";
				text += itoc(Min);
				TempLable->setString(text);
				break;
			}
			case PLAYER_CIRT_CHANCE:
				break;
			case PLAYER_ATTACK_DEFANCE:
				TempLable->setString(itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_Magic_Defance)).c_str());
				break;
			case PLAYER_MAGIC_ATTACK_DEFANCE:
				TempLable->setString(itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_Att_Defance)).c_str());
				break;
			case PLAYER_ATTACK_HIT_CHANCE:
				break;
			case PLAYER_MAGIC_HIT_CHANCE:
				break;
			case PLAYER_ATTACK_MISS_CHANCE:
				break;
			case PLAYER_MAGIC_ATTACK_MISS_CHANCE:
				break;
			case PLAYER_MOVE_SPEED:
				TempLable->setString(itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_MoveSpeed)).c_str());
				break;
			case PLAYER_JUMP_HIGH:
				TempLable->setString(itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetTotalValueNumber(Item_Value_JumpHigh)).c_str());
				break;
			case PLAYER_VALUE_VIEW_NAME_END:
				break;
			default:
				break;
			}
		}
	}
}

void PlayerUILayer::InitButtonMainUI()
{
	ButtonMainUI = CCSprite::create("ui/Button_UI_Main.png");
	ButtonSkillKeyBoardUI = CCSprite::create("ui/Button_Main_UI_KeyBoard.png");
	//ButtonSkillKeyBoardUI->setScale(UISize);
	ButtonMainUI->setScaleX(UISize);
	ButtonMainUI->setScaleY(0.9f);
	float Xtotal = ButtonMainUI->getBoundingBox().size.width + ButtonSkillKeyBoardUI->getBoundingBox().size.width;
	float StartPosx = (VisableSize.width - Xtotal) / 2;
	float final_StartPointX = StartPosx + ButtonMainUI->getBoundingBox().size.width / 2;
	ButtonMainUI->setPosition(final_StartPointX, ButtonMainUI->getBoundingBox().size.height / 2);
	addChild(ButtonMainUI);
	float posx = ButtonMainUI->getBoundingBox().origin.x + ButtonMainUI->getBoundingBox().size.width + ButtonSkillKeyBoardUI->getBoundingBox().size.width / 2 + 3;
	float posy = ButtonMainUI->getContentSize().height / 2;
	ButtonSkillKeyBoardUI->setPosition(posx, posy);
	Rect size = ButtonSkillKeyBoardUI->getBoundingBox();
	addChild(ButtonSkillKeyBoardUI);


	int KeyTag = SKILL_PRESS_KEY_BUTTON_TAG_START;
	for (size_t k = 0; k != 2; k++)
	{
		for (int i = 0; i != 14; i++)
		{
			CCSprite* KeyBordSlot = new CCSprite();
			KeyBordSlot->initWithFile("ui/bag_slot.png");
			float KeyBordSlot_Posx = ButtonMainUI->getBoundingBox().origin.x + ButtonMainUI->getBoundingBox().size.width;
			float KeyBordSlot_Posy = ButtonMainUI->getBoundingBox().size.height / 2;
			KeyBordSlot->setScale(0.9f);
			float po = KeyBordSlot->getBoundingBox().size.width;
			float posx = 21 + (i * (KeyBordSlot->getBoundingBox().size.width  + 3.2f));
			if (i > 3) posx += 10;
			float posy = 21;
			if (k == 1)
				posy += KeyBordSlot->getBoundingBox().size.height + 4;
			KeyBordSlot->setPosition(posx, posy);
			KeyBordSlot->autorelease();
			KeyBordSlot->setTag(KeyTag);
			ButtonSkillKeyBoardUI->addChild(KeyBordSlot);
			////float plus = (KeyBordSlot->getBoundingBox().size.width + 4.0f);
			////float PosX = (size.origin.x + 19.0f + (plus * i));
			////float PosY = (ButtonSkillKeyBoardUI->getBoundingBox().origin.y + KeyBordSlot->getBoundingBox().size.height / 2 + (k * KeyBordSlot->getBoundingBox().size.height + 5)) + 2;
			////if (i > 3)	PosX += 7;
			////KeyBordSlot->setPosition(PosX, PosY);
			//ButtonSkillKeyBoardUI->addChild(KeyBordSlot);
			//KeyTag++;
		}
	}
	std::string leveltext = "LV.";
	leveltext += itoc(Map_Scene::GetInstance()->GetLoadedPlayer()->GetLevel()).c_str();

	LevelText = CCLabelTTF::create(leveltext, "Airal", 14);
	NameText = CCLabelTTF::create(Map_Scene::GetInstance()->GetLoadedPlayer()->GetName().c_str(), "Airal", 13);
	ClassText = CCLabelTTF::create(Map_Scene::GetInstance()->GetLoadedPlayer()->GetClassString().c_str(), "Airal", 13);

	float asdf = ButtonMainUI->getBoundingBox().size.width;
	LevelText->setPosition(0 + LevelText->getBoundingBox().size.width / 2 + 2, ButtonMainUI->getContentSize().height / 2 - (asdf * 0.020f));
	LevelText->setHorizontalAlignment(TextHAlignment::LEFT);
	LevelText->setColor(ccc3(255, 255, 0));
	ButtonMainUI->addChild(LevelText);

	ClassText->setHorizontalAlignment(TextHAlignment::LEFT);
	ClassText->setPosition(LevelText->getBoundingBox().size.width * 2, ButtonMainUI->getContentSize().height / 2 - (asdf * 0.0115f));
	ClassText->setColor(ccc3(255, 255, 0));
	ButtonMainUI->addChild(ClassText);

	NameText->setHorizontalAlignment(TextHAlignment::LEFT);
	NameText->setPosition(LevelText->getBoundingBox().size.width * 2, ButtonMainUI->getContentSize().height / 2 - (asdf * 0.03f));
	ButtonMainUI->addChild(NameText);

	Button_Hp = CCProgressTimer::create(CCSprite::create("ui/Button_HP.png"));
	Button_Hp->setPosition(224.5, ButtonMainUI->getContentSize().height / 2.27);
	Button_Hp->setPercentage(0);
	Button_Hp->setBarChangeRate(ccp(1, 0));
	Button_Hp->setMidpoint(ccp(0, 0));
	Button_Hp->setType(kCCProgressTimerTypeBar);
	ButtonMainUI->addChild(Button_Hp);
	
	Button_Mp = CCProgressTimer::create(CCSprite::create("ui/Button_MP.png"));
	Button_Mp->setPosition(344.5, ButtonMainUI->getContentSize().height / 2.27);
	Button_Mp->setPercentage(0);
	Button_Mp->setBarChangeRate(ccp(1, 0));
	Button_Mp->setMidpoint(ccp(0, 0));
	Button_Mp->setType(kCCProgressTimerTypeBar);
	ButtonMainUI->addChild(Button_Mp);

	float exp_posx = ((Button_Mp->getPositionX() - Button_Hp->getPositionX()) / 2) + Button_Hp->getPositionX();
	Button_Exp = CCProgressTimer::create(CCSprite::create("ui/Button_EXP.png"));
	Button_Exp->setPosition(exp_posx, ButtonMainUI->getContentSize().height / 6.5f);
	Button_Exp->setPercentage(0);
	Button_Exp->setBarChangeRate(ccp(1, 0));
	Button_Exp->setMidpoint(ccp(0, 0));
	Button_Exp->setType(kCCProgressTimerTypeBar);
	ButtonMainUI->addChild(Button_Exp);
}

std::string PlayerUILayer::itoc(int _int)
{
	std::string returnstring = "";
	char msg[255];
	snprintf(msg, 255, "%d", _int);
	return msg;
}

bool PlayerUILayer::onTouchBegan(Touch *touch, Event *unused_event)
{
	//CCTexture2D *texture = CCTextureCache::sharedTextureCache()->addImage("Ground/Ground1.png");
	//Playerbag->setTexture(两种方法);
	Bag* Playerbag = (Bag*)getChildByTag(BAG_TAG);
	CCSprite* CharacterValueUI = (CCSprite*)getChildByTag(CHARACTER_VALUE_BACK_TAG);
	EquipUI* _EquipUI = (EquipUI*)getChildByTag(PLAYER_EQUIP_UI_TAG);
	CCSprite* DeadTalkClass = (CCSprite*)getChildByTag(PLAYER_DEAD_TALK_CLASS_TAG);
	if (Playerbag && CharacterValueUI && _EquipUI && DeadTalkClass)
	{
		Vec2 touchLocation = touch->getLocation();
		touchLocation = Playerbag->getParent()->convertToNodeSpace(touchLocation);
		Rect bBox = Playerbag->getBoundingBox();
		bool TouchBag = bBox.containsPoint(touchLocation);
		if (TouchBag && Playerbag->GetVisible())
		{
			int Touched = Playerbag->GetTouchedSlot(touch->getLocation());
			float x = touch->getLocation().x;
			float y = touch->getLocation().y;
			if (Touched > BAG_TAG && Touched <= BAG_SLOT_TAG_ENDED)
			{
				if (Slot* pSlot = Playerbag->GetSlot(Touched))
				{
					if (Item* pItem = pSlot->GetItem())
					{
						if (!IsTouuchWithItem())
						{
							SetTouchItem(pItem);
						}
					}
				}
			}
			else if (Touched == BAG_TAG)
			{
			}
			TouchedUI = Touched;
			return true;
		}
		touchLocation = CharacterValueUI->getParent()->convertToNodeSpace(touch->getLocation());
		Rect CharacterValueUIBox = CharacterValueUI->getBoundingBox();
		bool TouchCharacterValue = CharacterValueUIBox.containsPoint(touchLocation);
		if (TouchCharacterValue && CharacterValueUI->GetVisible())
		{
			TouchedUI = CharacterValueUI->getTag();
			return true;
		}

		touchLocation = _EquipUI->getParent()->convertToNodeSpace(touch->getLocation());
		Rect _EquipUIUIBox = _EquipUI->getBoundingBox();
		bool TouchEquipUI = _EquipUIUIBox.containsPoint(touchLocation);
		if (TouchEquipUI && _EquipUI->GetVisible())
		{
			int Touched = _EquipUI->GetTouchedSlot(touch->getLocation());
			TouchedUI = _EquipUI->getTag();
			if (Touched >= PLAYER_EQUIP_SLOT_START && Touched <= PLAYER_EQUIP_SLOT_END)
			{
				if (Slot* pSlot = _EquipUI->GetSlot(Touched))
				{
					if (Item* pItem = pSlot->GetItem())
					{
						if (!IsTouuchWithItem())
						{
							SetTouchItem(pItem);
						}
					}
				}
			}
			return true;
		}

		touchLocation = DeadTalkClass->getParent()->convertToNodeSpace(touch->getLocation());
		Rect DeadTalkClassBox = DeadTalkClass->getBoundingBox();
		bool TouchDeadTalkClass = DeadTalkClassBox.containsPoint(touchLocation);
		if (TouchDeadTalkClass && !Map_Scene::GetInstance()->GetLoadedPlayer()->IsAlive() && DeadTalkClass->isVisible())
		{
			CCSprite* ButtonSprite = (CCSprite*)DeadTalkClass->getChildByTag(PLAYER_DEAD_TALK_CLASS_BUTTON_TAG);
			touchLocation = ButtonSprite->getParent()->convertToNodeSpace(touch->getLocation());
			Rect ButtonSpriteBox = ButtonSprite->getBoundingBox();
			bool TouchButton = ButtonSpriteBox.containsPoint(touchLocation);
			if (TouchButton)
			{
				DeadTalkClass->setVisible(false);
				Map_Layer::GetInstance()->ReplaceMapForDeadPlayer();
			}
		}

		return false;
	}
	else
	{
		
	}
}

bool PlayerUILayer::IsThisUICanMoveByTouch(int TouchedUI)
{
	switch (TouchedUI)
	{
	case BAG_TAG:
	case CHARACTER_VALUE_BACK_TAG:
	case PLAYER_EQUIP_UI_TAG:
		return true;
	default:
		return false;
	}
}

void PlayerUILayer::ReSetMoveInfo()
{
	TouchMoveX = 0;
	TouchMoveY = 0;
	LastTouchX = 0;
	LastTouchY = 0;
	TouchedUI = -1;
}

void PlayerUILayer::MovingPlayerUIWitchTouch(CCSprite* pSprite, float NeedMoveX, float NeedMoveY)
{
	pSprite->setPosition(pSprite->getPosition().x + NeedMoveX, pSprite->getPosition().y + NeedMoveY);
	LastTouchX += NeedMoveX;
	LastTouchY += NeedMoveY;
	if (pSprite->getTag() == CHARACTER_VALUE_BACK_TAG)
	{
		CCSprite* CharacterDetailUI = (CCSprite*)getChildByTag(CHARACTER_VALUE_DETAIL_BACK_TAG);
		CharacterDetailUI->setPosition(CharacterDetailUI->getPosition().x + NeedMoveX, CharacterDetailUI->getPosition().y + NeedMoveY);
	}
	//ReSetMoveInfo();
}

void PlayerUILayer::onTouchMoved(Touch *touch, Event *unused_event)
{
	if (m_IsTouchWithItem && m_TouchedItem)
	{
		if (LastTouchX == 0 || LastTouchY == 0)
		{
			LastTouchX = touch->getLocation().x;
			LastTouchY = touch->getLocation().y;
			return;
		}
		else
		{
			TouchMoveX = touch->getLocation().x - LastTouchX;
			TouchMoveY = touch->getLocation().y - LastTouchY;
			MovingPlayerUIWitchTouch(m_TouchedItem, TouchMoveX, TouchMoveY);
		}
	}
	if (TouchedUI >= 0)
	{
		if (IsThisUICanMoveByTouch(TouchedUI))
		{
			if (CCSprite* PlayerUITemp = (CCSprite*)getChildByTag(TouchedUI))
			{
				//TouchMoveX = touch->getLocation().x - PlayerUITemp->getContentSize().width / 2;
				//TouchMoveY = touch->getLocation().y - PlayerUITemp->getContentSize().height / 2;
				//bool X, Y;
				//TouchMoveX > 0 ? X = true : X = false;
				//TouchMoveY > 0 ? Y = true : Y = false;
				//log("%f,%f", TouchMoveX, TouchMoveY);
				//log("touch : %f,%f", touch->getLocation().x, touch->getLocation().y);
				//log("Sprite : %f,%f", PlayerUITemp->getPosition().x, PlayerUITemp->getPosition().y);
				if (LastTouchX == 0 || LastTouchY == 0)
				{
					LastTouchX = touch->getLocation().x;
					LastTouchY = touch->getLocation().y;
					return;
				}
				else
				{
					TouchMoveX = touch->getLocation().x - LastTouchX;
					TouchMoveY = touch->getLocation().y - LastTouchY;
					MovingPlayerUIWitchTouch(PlayerUITemp, TouchMoveX, TouchMoveY);
					//ReSetPlayerItemViewWindowPostion();
				}
			}
		}
	}
}

void PlayerUILayer::ReSetPlayerItemViewWindowPostion(int NearByUI)
{
	CCSprite* ItemViewWindow_SultView	= (CCSprite*)getChildByTag(ITEM_VIEW_SULT_VIEW_TAG);
	CCSprite* ItemViewWindow_Sult		= (CCSprite*)getChildByTag(ITEM_VIEW_SULT_TAG);
	CCSprite* ItemViewWindow_Main		= (CCSprite*)getChildByTag(ITEM_VIEW_MAIN_TAG);
	CCSprite* PlayerBag;
	if (!NearByUI)
		PlayerBag = (CCSprite*)getChildByTag(BAG_TAG);
	else
		PlayerBag = (CCSprite*)getChildByTag(PLAYER_EQUIP_UI_TAG);
	if (ItemViewWindow_Main && ItemViewWindow_Sult && ItemViewWindow_SultView && PlayerBag)
	{
		float Left = PlayerBag->getBoundingBox().origin.x;
		float Right = Director::sharedDirector()->getVisibleSize().width - (PlayerBag->getBoundingBox().origin.x + PlayerBag->getBoundingBox().size.width);
		if (Left > Right)
		{
			ItemViewWindow_Main->setPosition(PlayerBag->getBoundingBox().origin.x - ItemViewWindow_Main->getBoundingBox().size.width / 2 - ItemViewWindow_Main->getBoundingBox().size.width, PlayerBag->getBoundingBox().origin.y + ItemViewWindow_Main->getBoundingBox().size.height / 2);
			ItemViewWindow_Sult->setPosition(PlayerBag->getBoundingBox().origin.x - ItemViewWindow_Main->getBoundingBox().size.width / 2 - ItemViewWindow_Main->getBoundingBox().size.width * 0.005, PlayerBag->getBoundingBox().origin.y + PlayerBag->getBoundingBox().size.height - ItemViewWindow_Sult->getBoundingBox().size.height / 2);
			ItemViewWindow_SultView->setPosition(PlayerBag->getBoundingBox().origin.x - ItemViewWindow_Main->getBoundingBox().size.width / 2 - ItemViewWindow_Main->getBoundingBox().size.width * 0.005, ItemViewWindow_Sult->getBoundingBox().origin.y - ItemViewWindow_SultView->getBoundingBox().size.height / 2);
		}
		else
		{
			ItemViewWindow_Main->setPosition(PlayerBag->getBoundingBox().origin.x + PlayerBag->getBoundingBox().size.width + ItemViewWindow_Main->getBoundingBox().size.width / 2, PlayerBag->getBoundingBox().origin.y + ItemViewWindow_Main->getBoundingBox().size.height / 2);
			ItemViewWindow_Sult->setPosition(ItemViewWindow_Main->getBoundingBox().origin.x + ItemViewWindow_Main->getBoundingBox().size.width + ItemViewWindow_Main->getBoundingBox().size.width / 2, PlayerBag->getBoundingBox().origin.y + PlayerBag->getBoundingBox().size.height - ItemViewWindow_Sult->getBoundingBox().size.height / 2);
			ItemViewWindow_SultView->setPosition(ItemViewWindow_Sult->getPositionX(), ItemViewWindow_Sult->getBoundingBox().origin.y - ItemViewWindow_SultView->getBoundingBox().size.height / 2);
		}
	}
}

bool PlayerUILayer::IsTouchedSprite(Touch* pTouch, CCSprite* pSprite)
{
	Vec2 touchLocation = pTouch->getLocation(); // Get the touch position
	touchLocation = pSprite->getParent()->convertToNodeSpace(touchLocation);
	Rect bBox = pSprite->getBoundingBox();
	bool TouchBag = bBox.containsPoint(touchLocation);

	return TouchBag;
}

void PlayerUILayer::onTouchEnded(Touch *touch, Event *unused_event)
{
	if (m_IsTouchWithItem && m_TouchedItem)
	{
		Bag* Playerbag = (Bag*)getChildByTag(BAG_TAG);
		if (Playerbag && _EquipUI)
		{
			if (IsTouchedSprite(touch,Playerbag) && Playerbag->GetVisible())
			{
				int Touched = Playerbag->GetTouchedSlot(touch->getLocation());
				float x = touch->getLocation().x;
				float y = touch->getLocation().y;
				if (Touched > BAG_TAG && Touched <= BAG_SLOT_TAG_ENDED)
				{
					if (Slot* NewSlot = Playerbag->GetSlot(Touched))
					{
						if (NewSlot->IsEmptySlot())
						{
							if (Slot* OldSlot = GetComeFromSlot())
							{
								OldSlot->ReSetSlotItem();
								m_TouchedItem->setParent(nullptr);
								m_TouchedItem->setPosition(NewSlot->getContentSize().width / 2, NewSlot->getContentSize().height / 2);
								NewSlot->SetItem(m_TouchedItem);
								NewSlot->SetItemGuid(m_TouchedItem->GetGuid());
								m_TouchedItem->SetSlot(NewSlot->getTag());
								NewSlot->addChild(m_TouchedItem);
								OldSlot->removeAllChildren();
							}
						}
						else if (Slot* OldSlot = GetComeFromSlot())
						{
							if (OldSlot->GetItem() == NewSlot->GetItem())
							{
								m_TouchedItem->setPosition(OldSlot->getContentSize().width / 2, OldSlot->getContentSize().height / 2);
							}
							else
							{
								Playerbag->SwapItem(OldSlot, NewSlot);
							}
						}
					}
				}
				else if (Slot* OldSlot = GetComeFromSlot())
				{
					m_TouchedItem->setPosition(OldSlot->getContentSize().width / 2, OldSlot->getContentSize().height / 2);
				}
			}
			else if (IsTouchedSprite(touch, _EquipUI) && _EquipUI->GetVisible())
			{
				int Touched = _EquipUI->GetTouchedSlot(touch->getLocation());
				if (Touched >= PLAYER_EQUIP_SLOT_START && Touched <= PLAYER_EQUIP_SLOT_END)
				{
					if (Slot* NewSlot = _EquipUI->GetSlot(Touched))
					{
						if (NewSlot->IsEmptySlot())
						{
							if (!Map_Scene::GetInstance()->GetLoadedPlayer()->CanEquipItem(NewSlot->getTag(), m_TouchedItem))
							{
								if (Slot* OldSlot = GetComeFromSlot())
									m_TouchedItem->setPosition(OldSlot->getContentSize().width / 2, OldSlot->getContentSize().height / 2);
								return;
							}
							if (Slot* OldSlot = GetComeFromSlot())
							{
								OldSlot->ReSetSlotItem();
								m_TouchedItem->setParent(nullptr);
								m_TouchedItem->setPosition(NewSlot->getContentSize().width / 2, NewSlot->getContentSize().height / 2);
								NewSlot->SetItem(m_TouchedItem);
								NewSlot->SetItemGuid(m_TouchedItem->GetGuid());
								m_TouchedItem->SetSlot(NewSlot->getTag());
								NewSlot->addChild(m_TouchedItem);
								OldSlot->removeAllChildren();
								Map_Scene::GetInstance()->GetLoadedPlayer()->SetUpdatePlayerValue();
							}
						}
						else
						{
							//如果不可以装备
							if (!Map_Scene::GetInstance()->GetLoadedPlayer()->CanEquipItem(NewSlot->getTag(), m_TouchedItem))
							{
								//退回原位置
								if (Slot* OldSlot = GetComeFromSlot())
									m_TouchedItem->setPosition(OldSlot->getContentSize().width / 2, OldSlot->getContentSize().height / 2);
							}
							else
							{
								if (Slot* OldSlot = GetComeFromSlot())
								{
									Playerbag->SwapItem(OldSlot, NewSlot);
									Map_Scene::GetInstance()->GetLoadedPlayer()->SetUpdatePlayerValue();
								}
							}
						}
					}
					else
					{

						if (Slot* OldSlot = GetComeFromSlot())
							m_TouchedItem->setPosition(OldSlot->getContentSize().width / 2, OldSlot->getContentSize().height / 2);
					}
				}
			}
			else
			{

				if (Slot* OldSlot = GetComeFromSlot())
				{
					sWorld->GetLoadedPlayer()->RemoveItemFromSlot(OldSlot);
				}
			}
		}
		m_IsTouchWithItem = false;
		m_TouchedItem = nullptr;
	}
	ReSetMoveInfo();
}

Slot* PlayerUILayer::GetComeFromSlot()
{
	Bag* Playerbag = (Bag*)getChildByTag(BAG_TAG);
	Slot* OldSlot;
	switch (m_TouchedItem->GetComeFrom())
	{
	case COMEFROM_BAG:
		OldSlot = Playerbag->GetSlot(m_TouchedItem->GetBagSlot());
		break;
	case COMEFROM_EQUIP:
		OldSlot = _EquipUI->GetSlot(m_TouchedItem->GetBagSlot());
		break;
	}
	return OldSlot;
}

void PlayerUILayer::CheckCCProgress()
{
	if (Player* _Player = Map_Scene::GetInstance()->GetLoadedPlayer())
	{
		float hp_new = _Player->GetInt32Value(VALUE_HP);
		float hp_max = _Player->GetTotalValueNumber(Item_Value_Heath);
		float hp = (hp_new / hp_max) * 100;
		int modify_hp = hp - Button_Hp->getPercentage();
		if (modify_hp)
		{
			modify_hp > 0 ? Button_Hp->setPercentage(Button_Hp->getPercentage() + 1) : Button_Hp->setPercentage(Button_Hp->getPercentage() - 1);
		}

		float mp_now = _Player->GetInt32Value(VALUE_MP);
		float mp_max = _Player->GetTotalValueNumber(Item_Value_Mana);
		float mp_press = (mp_now / mp_max) * 100;
		int modify_mp = mp_press - Button_Mp->getPercentage();
		if (modify_mp)
		{
			modify_mp > 0 ? Button_Mp->setPercentage(Button_Mp->getPercentage() + 1) : Button_Mp->setPercentage(Button_Mp->getPercentage() - 1);
		}

		float need = _Player->GetNextLevelExp();
		if (need > 0)
		{
			float expnow = _Player->GetInt32Value(EXP);
			float _Exp = (expnow / need) * 100;
			int progressnow = Button_Exp->getPercentage();
			int modify_exp = _Exp - progressnow;
			if (modify_exp)
			{
				modify_exp > 0 ? Button_Exp->setPercentage(Button_Exp->getPercentage() + 1) : Button_Exp->setPercentage(Button_Exp->getPercentage() - 1);
			}
		}
		else
		{
			if (Button_Exp->getPercentage() != 100)
				Button_Exp->setPercentage(100);
		}
	}
	//float level_precentage = _testporgress->getPercentage();
	//level_precentage += 1;
	//
	//if (level_precentage < 60)
	//{
	//	_testporgress->setPercentage(level_precentage);
	//}
}

void PlayerUILayer::AddLootInfoToLayer(std::string Name)
{
	std::string plus = "你获取了 [";
	plus += Name;
	plus += "];";

	CCLabelTTF* TempLable = new CCLabelTTF();
	TempLable->initWithString(plus.c_str(), "Arial", 14, Size::ZERO, TextHAlignment::RIGHT, TextVAlignment::CENTER);
	TempLable->autorelease();
	TempLable->setPosition(Director::sharedDirector()->getVisibleSize().width - TempLable->getBoundingBox().size.width / 2, Director::sharedDirector()->getVisibleSize().height * 0.1);
	CCDelayTime* pdelay = CCDelayTime::create(3.0f);
	CCFadeOut* pFadeOut = CCFadeOut::create(1.0f);
	CCSequence* spawn = CCSequence::create(pdelay, pFadeOut, CallFunc::create(CC_CALLBACK_0(PlayerUILayer::RemoveLableFromLootLayer, this, TempLable)), NULL);
	TempLable->runAction(spawn);
	for (int i = 0; i != LootInfo.size(); i++)
	{
		LootInfo.at(i)->setPositionY(LootInfo.at(i)->getPositionY() + 5 + TempLable->getBoundingBox().size.height);
	}
	addChild(TempLable);
	LootInfo.push_back(TempLable);
}

void PlayerUILayer::RemoveLableFromLootLayer(CCLabelTTF* pLable)
{
	if (LootInfo.size())
	{
		for (std::vector<CCLabelTTF*>::iterator itr = LootInfo.begin(); itr != LootInfo.end(); itr++)
		{
			if (*itr == pLable)
			{
				LootInfo.erase(itr);
				break;
			}
		}
	}
	pLable->removeFromParentAndCleanup(true);
}

void PlayerUILayer::SendPlayerNotify(std::string _Notify)
{
	std::string plus = "系统提示 : ";
	plus += _Notify;
	plus += ";";

	CCLabelTTF* TempLable = new CCLabelTTF();
	TempLable->initWithString(plus.c_str(), "Arial", 15, Size::ZERO, TextHAlignment::LEFT, TextVAlignment::CENTER);
	TempLable->autorelease();
	TempLable->setPosition(Director::sharedDirector()->getVisibleSize().width / 2, Director::sharedDirector()->getVisibleSize().height * 0.8);
	TempLable->setColor(ccc3(255, 0, 0));
	CCDelayTime* pdelay = CCDelayTime::create(3.0f);
	CCFadeOut* pFadeOut = CCFadeOut::create(1.0f);
	CCSequence* spawn = CCSequence::create(pdelay, pFadeOut, CallFunc::create(CC_CALLBACK_0(PlayerUILayer::ReMovePlayerNotify, this, TempLable)), NULL);
	TempLable->runAction(spawn);
	for (int i = 0; i != PlayerNotify.size(); i++)
	{
		PlayerNotify.at(i)->setPositionY(PlayerNotify.at(i)->getPositionY() + 5 + TempLable->getBoundingBox().size.height);
	}
	addChild(TempLable);
	PlayerNotify.push_back(TempLable);
}

void PlayerUILayer::ReMovePlayerNotify(CCLabelTTF* pLable)
{
	if (PlayerNotify.size())
	{
		for (std::vector<CCLabelTTF*>::iterator itr = PlayerNotify.begin(); itr != PlayerNotify.end(); itr++)
		{
			if (*itr == pLable)
			{
				PlayerNotify.erase(itr);
				break;
			}
		}
	}
	pLable->removeFromParentAndCleanup(true);
}

void PlayerUILayer::SetCharacterValueVisable(bool _vis)
{
	CharacterValue_Main_UI_Back->setVisible(_vis);
	CharacterValue_Detail_UI_Back->setVisible(_vis);
}

void PlayerUILayer::SetItemViewVisable(bool _vis)
{
	CCSprite* ItemViewWindow_SultView = (CCSprite*)getChildByTag(ITEM_VIEW_SULT_VIEW_TAG);
	CCSprite* ItemViewWindow_Sult = (CCSprite*)getChildByTag(ITEM_VIEW_SULT_TAG);
	CCSprite* ItemViewWindow_Main = (CCSprite*)getChildByTag(ITEM_VIEW_MAIN_TAG);
	if (ItemViewWindow_Main && ItemViewWindow_Sult && ItemViewWindow_SultView)
	{
		ItemViewWindow_Main->setVisible(_vis);
		ItemViewWindow_Sult->setVisible(_vis);
		ItemViewWindow_SultView->setVisible(_vis);
	}
}
void PlayerUILayer::ReSetItemViewStringForShow(Slot* pSlot, int PlayerUITag)
{
	Item* TempItem = pSlot->GetItem();
	Player* TempPlayer = Map_Scene::GetInstance()->GetLoadedPlayer();
	if (TempPlayer && TempItem && _EquipUI)
	{
		CCSprite * sbusp = (CCSprite*)getChildByTag(ITEM_VIEW_MAIN_TAG)->getChildByTag(ITEM_VIEW_MAIN_IMAGE)->getChildByTag(ITEM_VIEW_MAIN_IMAGE_SUB_VIEW);
		char url[255];
		snprintf(url, 255, "ItemImage/%s.png", TempItem->GetUrl().c_str());
		sbusp->setTexture(url);
		sbusp->setScale(2.0f);
		TempPlayer->GetItemViewTTF(NAME_TITLE)->setString(TempItem->GetName().c_str());
		TempItem->IsSoulBonding() ? TempPlayer->GetItemViewTTF(BONDING_TYPE)->setString("不可交易") : TempPlayer->GetItemViewTTF(BONDING_TYPE)->setString("可交易");
		char msg[255];
		snprintf(msg, 255, "·REQ LEV: %d", TempItem->GetNeedLevel());
		TempPlayer->GetItemViewTTF(REQUIRE_LEVEL)->setString(msg);
		std::string ChangeText = "装备分类 : ";
		ChangeText += TempItem->GetItemEquipSlotString();
		ChangeText += "\n";
		for (int i = Item_Value_None; i != Item_Value_Defance_Ingnore; i++)
		{
			int Number = TempItem->GetItemTotalModifyValue((ItemValue)i);
			if (Number)
			{
				ChangeText += TempItem->GetItemTotalModifyValueString((ItemValue)i, Number);
			}
		}
		TempPlayer->GetItemViewTTF(ITEM_VALUES)->setString(ChangeText.c_str());
		ReSetPlayerItemViewWindowPostion(PlayerUITag);
	}
}

void PlayerUILayer::CheckMouseAction()
{
	if (m_MouseMoveFlag == FLAG_CHANGEED)
	{
		if (m_MouseMoveToTag >= BAG_SLOT_TAG_BEGIN && m_MouseMoveToTag <= BAG_SLOT_TAG_ENDED)
		{
			if (Bag* Playerbag = (Bag*)getChildByTag(BAG_TAG))
			{
				if (Slot* pSlot = (Slot*)Playerbag->getChildByTag(m_MouseMoveToTag))
				{
					if (!pSlot->IsEmptySlot())
					{
						ReSetItemViewStringForShow(pSlot);
						SetItemViewVisable(true);
					}
				}
			}
		}
		else if (m_MouseMoveToTag >= PLAYER_EQUIP_SLOT_START && m_MouseMoveToTag <= PLAYER_EQUIP_SLOT_END && _EquipUI)
		{
			if (Slot* pSlot = (Slot*)_EquipUI->getChildByTag(m_MouseMoveToTag))
			{
				if (!pSlot->IsEmptySlot())
				{
					ReSetItemViewStringForShow(pSlot, 1);
					SetItemViewVisable(true);
				}
			}
		}
		else
		{
			SetItemViewVisable(false);
		}
		m_MouseMoveFlag = FLAG_NONE;
	}
}

void PlayerUILayer::update(float second)
{
	CheckCCProgress();
	CheckMouseAction();
}

Map_Layer::~Map_Layer(){}


Map_Layer::Map_Layer()
{
	player = Map_Scene::GetInstance()->GetLoadedPlayer();
	m_MapID = Map_Scene::GetInstance()->GetNowMapID();
	_MoveType.Down = false;
	_MoveType.Left = false;
	_MoveType.Right = false;
	_MoveType.Up = false;
	_Facing = Facing::left;
	Resettimer = -99;
	_Map_Layer = this;
	m_IsBagOpened = false;
	Spells.clear();
}

Map_Layer* Map_Layer::GetInstance()
{
	if (_Map_Layer == nullptr)
	{
		return nullptr;
	}
	return _Map_Layer;
}

void Map_Layer::ReplaceMapForDeadPlayer()
{
	CCDelayTime* DelayTime = CCDelayTime::create(2.0f);
	CCSequence* MapReplaceSeque = CCSequence::create(CallFunc::create(CC_CALLBACK_0(Map_Layer::CreateBlackBackGround, this)), DelayTime, CallFunc::create(CC_CALLBACK_0(Map_Layer::RemoveEveryThing, this)), NULL);
	runAction(MapReplaceSeque);
}

void Map_Layer::CreateBlackBackGround()
{
	CCSprite* Black_Back_Ground = CCSprite::create("ui/Black_Back_Ground.png");
	Black_Back_Ground->setPosition(VisableSize.width / 2, VisableSize.height / 2);
	Black_Back_Ground->setScale(20.0f);
	Black_Back_Ground->setOpacity(0);
	addChild(Black_Back_Ground);
	CCFadeIn* MapReplaceFadeIn = CCFadeIn::create(1.5f);
	Black_Back_Ground->runAction(MapReplaceFadeIn);
}

void Map_Layer::RemoveEveryThing()
{
	unscheduleUpdate();
	player->retain();
	ReSetAllVectorsAndMaps();
	removeAllChildren();
	m_MapID = 1;
	player->Revive();
	InitMap();
	AddMonsterToMap();
	addChild(player);
	scheduleUpdate();
	CCSprite* Black_Back_Ground = CCSprite::create("ui/Black_Back_Ground.png");
	Black_Back_Ground->setPosition(VisableSize.width / 2, VisableSize.height / 2);
	Black_Back_Ground->setScale(20.0f);
	Black_Back_Ground->setTag(BLACK_BACK_GROUND_TAG);
	addChild(Black_Back_Ground);
	CCFadeOut* MapReplaceFadeIn = CCFadeOut::create(1.5f);
	CCDelayTime* _delay = CCDelayTime::create(2.0f);
	CCSequence* BlackFadeOutSeq = CCSequence::create(_delay, MapReplaceFadeIn, CallFunc::create(CC_CALLBACK_0(Map_Layer::RemoveBlackBackGround, this)), NULL);
	Black_Back_Ground->runAction(BlackFadeOutSeq);
}

void Map_Layer::RemoveBlackBackGround()
{
	if (CCSprite* back = (CCSprite*)getChildByTag(BLACK_BACK_GROUND_TAG))
	{
		back->removeFromParentAndCleanup(true);
	}
}

void Map_Layer::ReSetAllVectorsAndMaps()
{
	MapGround.clear();
	Backs.clear();
	Threes.clear();
	Clouds.clear();
	Monsters.clear();
	Loots.clear();
	Spells.clear();
}

bool Map_Layer::init()
{
	bool bRef = false;
	do
	{
		CC_BREAK_IF(!CCLayer::init());
		auto listener = EventListenerKeyboard::create();
		listener->onKeyPressed = CC_CALLBACK_2(Map_Layer::onKeyPressed, this);
		listener->onKeyReleased = CC_CALLBACK_2(Map_Layer::onKeyReleased, this);
		_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);
		InitMap();
		addChild(player);
		player->InitBag();
		CCSize s = CCDirector::sharedDirector()->getWinSize();

		//m_grossini->setPosition(CCPointMake(-200, s.height / 2));
		//CCActionInterval* move = CCMoveBy::create(2, CCPointMake(s.width * 3, 0));
		//CCActionInterval* move_back = move->reverse();
		//CCFiniteTimeAction* seq = CCSequence::create(move, move_back, NULL);
		//CCAction* rep = CCRepeatForever::create((CCActionInterval*)seq);
		//
		//runAction(rep);

		runAction(CCFollow::create(player, CCRectMake(0, 0, s.width * 2, VisableSize.height)));
		AddMonsterToMap();
		scheduleUpdate();
		bRef = true;
	} while (0);

	return bRef;
}

void Map_Layer::InitMap()
{
	Backs.clear();
	for (size_t i = 0; i < 4; i++)
	{
		CCSprite* Ground = new CCSprite();
		Ground->initWithFile("backpicture/back1.jpg");
		Ground->autorelease();
		Backs.push_back(Ground);
		Ground->setScale(1.2f);
		CCRect rect = Ground->boundingBox();
		Ground->setPosition(0 + (i * rect.size.width), VisableSize.height / 2);
		addChild(Backs.at(i));
	}

	Clouds.clear();
	for (size_t i = 0; i < 8; i++)
	{
		CCSprite* Ground = new CCSprite();
		Ground->initWithFile("decorate/outher1.png");
		Ground->autorelease();
		Clouds.push_back(Ground);
		CCRect rect = Ground->boundingBox();
		Ground->setPosition(0 + (i * rect.size.width), VisableSize.height / 1.7);
		addChild(Clouds.at(i));
	}

	Threes.clear();
	for (size_t i = 0; i < 18; i++)
	{
		CCSprite* Ground = new CCSprite();
		Ground->initWithFile("decorate/outher5.png");
		Ground->autorelease();
		Threes.push_back(Ground);
		CCRect rect = Ground->boundingBox();
		Ground->setPosition(0 + (i * rect.size.width), VisableSize.height / 5);
		addChild(Threes.at(i));
	}

	MapGround.clear();
	for (size_t i = 0; i < 28; i++)
	{
		CCSprite* Ground = new CCSprite();
		Ground->initWithFile("Ground/Ground1.png");
		Ground->autorelease();
		MapGround.push_back(Ground);
		CCRect rect = Ground->boundingBox();
		//Ground->setPosition(0 + (i * rect.size.width * 2), 100);
		if (i == 8)
			Ground->setPosition(0 + (i * rect.size.width), Ground->getBoundingBox().size.height / 2 + 40);
		else
			Ground->setPosition(0 + (i * rect.size.width), Ground->getBoundingBox().size.height / 2);
	}
	for (size_t i = 0; i < MapGround.size(); i++)
	{
		addChild(MapGround.at(i));
	}
}

void Map_Layer::RemoveMonsterFromMapWhenDead(Monster* pMonster)
{
	for (std::vector<Monster*>::iterator itr = Monsters.begin(); itr != Monsters.end(); itr++)
	{
		if (pMonster == *itr)
		{
			Monsters.erase(itr);
			break;
		}
	}
}
void Map_Layer::AddLoot(Loot* pLoot)				
{ 
	Loots.push_back(pLoot); 
}

void Map_Layer::RemoveLoot(Loot* pLoot)
{
	if (Loots.size())
	for (std::vector<Loot*>::iterator itr = Loots.begin(); itr != Loots.end(); itr++)
	{
		if (pLoot == *itr)
		{
			Loots.erase(itr);
			break;
		}
	}
}

void Map_Layer::AddMonsterToMap()
{
	std::vector<MapInfo> infovector = Map_Scene::GetInstance()->GetMapInfoVector(m_MapID);
	std::map<int, MonstersBaseInfo> tempmap = Map_Scene::GetInstance()->GetMonsterMap();
	if (tempmap.empty() || infovector.empty())
		return;

	for (int i = 0; i != infovector.size(); i++)
	{
		std::map<int, MonstersBaseInfo>::iterator itr = tempmap.find(infovector.at(i).MonsterEntry);
		if (itr != tempmap.end())
		{
			Monster* Temp = new Monster(itr->second.Entry, itr->second.maxheath, itr->second.Attack_Power, itr->second.Defance, itr->second.MissChance, itr->second.CritChance, itr->second.Level, itr->second.Loot, itr->second.reswardexp, itr->second.rewardmoney, itr->second.imageurl, itr->second.deadsoundurl, itr->second.takedamagesoundurl);
			Temp->setPosition(player->GetPos().origin.x + rand() % 200, 700);
			addChild(Temp);
			Monsters.push_back(Temp);
		}
	}
}

void Map_Layer::CleanUpSpellWhenDelete(Unit* pUnit)
{
	for (UnitSpellMap::iterator itr = Spells.begin(); itr != Spells.end(); itr++)
	{
		if (itr->first == pUnit)
		{
			Spells.erase(itr);
			break;
		}
	}
}

void Map_Layer::AddSpellToMap(Unit*pUnit, Spell* pSpell)
{
	CC_ASSERT(pUnit);
	CC_ASSERT(pSpell);
	Spells[pUnit] = pSpell;
}

void Map_Layer::RemoveUnitSpellFromMap(Unit* pUnit)
{
	if (Spells.empty())
	{
		log("Removing Spell From SpellMap But Map Is EMPTY!");
		return;
	}
	for (UnitSpellMap::iterator itr = Spells.begin(); itr != Spells.end(); itr++)
	{
		if (itr->first == pUnit && itr->second)
		{
			//itr->second->ReleaseSpell();
			itr->second = nullptr;
			return;
		}
	}
	log("Removing Spell From SpellMap But There Is NO SPELL!");
}

bool Map_Layer::IsUnitCastingSpell(Unit* pUnit)
{
	if (Spells.empty())
		return false;

	for (UnitSpellMap::iterator itr = Spells.begin(); itr != Spells.end(); itr++)
	{
		if (itr->first == pUnit)
		if (itr->second)
			return true;
	}
	return false;
}

void Map_Layer::CheckLoot()
{
	if (!player || Loots.empty())
		return;

	for (int i = 0; i < Loots.size(); i++)
	{
		if (IsInSide(player,Loots.at(i)))
		{
			Loots.at(i)->IsLootingByPlayer(player);
			return;
		}
	}
}

void Map_Layer::onKeyPressed(EventKeyboard::KeyCode keyCode, Event* event)
{
	if (!player->IsAlive())
		return;
	switch (keyCode)
	{
	case cocos2d::EventKeyboard::KeyCode::KEY_CTRL:
	{
		if (!player->IsCastingSpell())
		{
			player->CastSpell(ATTACK_NORMAL);
			Resettimer = 0.5f;
		}
		break;
	}
	case cocos2d::EventKeyboard::KeyCode::KEY_Z:
	{
		CheckLoot();
		break;
	}
	case cocos2d::EventKeyboard::KeyCode::KEY_I:
	{
		if (m_IsBagOpened)
		{
			m_IsBagOpened = false;
			player->GetBag()->setVisible(false);
		}
		else
		{
			m_IsBagOpened = true;
			player->GetBag()->setVisible(true);
		}
		break;
	}
	case cocos2d::EventKeyboard::KeyCode::KEY_E:
	{
		if (PlayerUILayer::GetInstance()->GetCharacterEquipUIVisable())
			PlayerUILayer::GetInstance()->SetCharacterEquipUIVisable(false);
		else
			PlayerUILayer::GetInstance()->SetCharacterEquipUIVisable(true);
		break;
	}
	case cocos2d::EventKeyboard::KeyCode::KEY_C:
	{
		if (PlayerUILayer::GetInstance()->GetCharacterValueVisable())
			PlayerUILayer::GetInstance()->SetCharacterValueVisable(false);
		else
			PlayerUILayer::GetInstance()->SetCharacterValueVisable(true);
		break;
	}
	case cocos2d::EventKeyboard::KeyCode::KEY_ALT:
	{
		if (!player->IsJumping() && !CanMoveFall(player))
		{
			 player->DoAction(JUMP);
			 if (_MoveType.Right)
				 player->Jump(RIGHT);
			 else if (_MoveType.Left)
				 player->Jump(LEFT);
			 else player->Jump();
			 Resettimer = 0.4f;
		}
		break;
	}
	case cocos2d::EventKeyboard::KeyCode::KEY_DOWN_ARROW:
		_MoveType.Down = true;
		break;
	case cocos2d::EventKeyboard::KeyCode::KEY_LEFT_ARROW:
		_MoveType.Left = true;
		break;
	case cocos2d::EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
		_MoveType.Right = true;
		break;
	case cocos2d::EventKeyboard::KeyCode::KEY_UP_ARROW:
		_MoveType.Up = true;
		break;
	default:
		break;
	}
}

void Map_Layer::onKeyReleased(EventKeyboard::KeyCode keyCode, Event* event)
{
	switch (keyCode)
	{
	case cocos2d::EventKeyboard::KeyCode::KEY_DOWN_ARROW:
	{
		_MoveType.Down = false;
		break;
	}
	case cocos2d::EventKeyboard::KeyCode::KEY_LEFT_ARROW:
		_MoveType.Left = false;
		break;
	case cocos2d::EventKeyboard::KeyCode::KEY_RIGHT_ARROW:
		_MoveType.Right = false;
		break;
	case cocos2d::EventKeyboard::KeyCode::KEY_UP_ARROW:
		_MoveType.Up = false;
		break;
	default:
		break;
	}
}

bool Map_Layer::IsInSide(CCSprite* Checked, CCSprite* Checker)/*checked在checker内*/
{
	return Checked->boundingBox().intersectsRect(Checker->boundingBox());
}

float Map_Layer::GetGroundPointY()
{
	CCRect rect = player->boundingBox();
	float PlayerLeftButtonX = rect.origin.x;
	float PlayerRightButtonX = rect.origin.x + rect.size.width;
	float PlayerButtonY = rect.origin.y;
	for (int i = 0; i != MapGround.size(); i++)
	{
		CCRect rect = MapGround.at(i)->boundingBox();
		float GroundTopY = rect.origin.y + rect.size.height;
		float GroundLeftTopX = rect.origin.x;
		float GroundRightTopX = GroundLeftTopX + rect.size.width;
		if ((PlayerLeftButtonX <= GroundRightTopX && PlayerLeftButtonX >= GroundLeftTopX) || (PlayerRightButtonX >= GroundLeftTopX && PlayerRightButtonX <= GroundRightTopX))
		{
			if (PlayerButtonY <= GroundTopY)
			{
				return GroundTopY;
			}
		}
	}
}

bool Map_Layer::CanMoveFall(CCSprite* Checked)
{
	CCRect rect = Checked->boundingBox();
	float PlayerLeftButtonX = rect.origin.x;
	float PlayerRightButtonX = rect.origin.x + rect.size.width;
	float PlayerButtonY = rect.origin.y;
	float GroundTopY;
	float GroundLeftTopX;
	float GroundRightTopX;
	bool CanFall = true;
	for (int i = 0; i < MapGround.size(); i++)
	{
		CCRect rect = MapGround.at(i)->boundingBox();
		GroundTopY		= rect.origin.y + rect.size.height;
		GroundLeftTopX	= rect.origin.x;
		GroundRightTopX	= GroundLeftTopX + rect.size.width;
		if ((PlayerLeftButtonX <= GroundRightTopX && PlayerLeftButtonX >= GroundLeftTopX) || (PlayerRightButtonX >= GroundLeftTopX && PlayerRightButtonX <= GroundRightTopX))
		{
			if (PlayerButtonY <= GroundTopY)
			{
				CanFall = false;
			}
		}
	}

	if (PlayerButtonY < 50.0f)
		CanFall = false;

	if (((Unit*)Checked)->GetTypeId() == TypeID_Player)
	if (Player* _player = (Player*)Checked)
	if (_player->IsDisableFall())
		CanFall = false;

	return CanFall;
}


bool Map_Layer::CanMoveLeft(CCSprite* pChecked)
{
	CCRect Playerrect = pChecked->boundingBox();
	float PlayerLeftButtonX = Playerrect.origin.x;
	float PlayerRightButtonX = PlayerLeftButtonX + Playerrect.size.width;
	float PlayerLeftButtonY = Playerrect.origin.y;
	float PlayerLeftTopY = PlayerLeftButtonY + Playerrect.size.height;
	bool CanLeft = true;
	for (int i = 0; i < MapGround.size(); i++)
	{
		CCRect rect = MapGround.at(i)->boundingBox();
		float MapGroundRightButtonX = rect.origin.x + rect.size.width;
		float MapGroundRightButtonY = rect.origin.y;
		float MapGroundRightTopY = MapGroundRightButtonY + rect.size.height;
		float MapGroundLeftButtonX = rect.origin.x;

		if ((PlayerLeftButtonY >= MapGroundRightButtonY && PlayerLeftButtonY + 8.0f <= MapGroundRightTopY) || (PlayerLeftTopY <= MapGroundRightTopY && PlayerLeftTopY >= MapGroundRightButtonY))
		{
			if (PlayerLeftButtonX <= MapGroundRightButtonX)
				CanLeft = false;
			if (PlayerRightButtonX <= MapGroundLeftButtonX + 1.0f)
				CanLeft = true;
		}
	}


	return CanLeft;
}

bool Map_Layer::CanMoveRight(CCSprite* pChecked)
{
	CCRect Playerrect = pChecked->boundingBox();
	float PlayerRightTopY = Playerrect.origin.y + Playerrect.size.height;
	float PlayerRightButtonY = Playerrect.origin.y;
	float PlayerRightButtonX = Playerrect.origin.x + Playerrect.size.width;
	float PlayerLeftButtonX = Playerrect.origin.x;
	bool CanRight = true;

	for (int i = 0; i != MapGround.size(); i++)
	{
		CCRect rect = MapGround.at(i)->boundingBox();
		float MapGroundLeftButtonY = rect.origin.y;
		float MapGroundLeftTopY = MapGroundLeftButtonY + rect.size.height;
		float MapGroundLeftButtonX = rect.origin.x;

		if ((PlayerRightTopY <= MapGroundLeftTopY && PlayerRightTopY >= MapGroundLeftButtonY) || (PlayerRightButtonY >= MapGroundLeftButtonY && PlayerRightButtonY + 8.0f <= MapGroundLeftTopY))
		{
			if (PlayerLeftButtonX < MapGroundLeftButtonX)
			if (PlayerRightButtonX >= MapGroundLeftButtonX)
				CanRight = false;
		}
	}

	if (pChecked->getBoundingBox().origin.x + pChecked->getBoundingBox().size.width > END_OF_MAP_LAYER_RIGHT)
		CanRight = false;

	return CanRight;
}

void Map_Layer::update(float second)
{
	if (CanMoveFall(player))
	{
		float GroundPosY = GetGroundPointY();
		float TempPoint = player->getPositionY() - (4.0f * player->GetFallingSpeed());
		player->setPositionY(TempPoint/*GroundPosY > TempPoint ? GroundPosY : TempPoint*/);
		player->SetFallingSpeed(player->GetFallingSpeed() + second);
	}
	else if (player->GetFallingSpeed() != 1.0f)
		player->SetFallingSpeed(1.0f);

	for (int i = 0; i < Monsters.size(); i++)
	{
		Monster* TempMonster = Monsters.at(i);
		if (CanMoveFall(TempMonster))
		{
			float GroundPosY = GetGroundPointY();
			float TempPoint = TempMonster->getPositionY() - (4.0f * TempMonster->GetFallingSpeed());
			TempMonster->setPositionY(TempPoint/*GroundPosY > TempPoint ? GroundPosY : TempPoint*/);
			TempMonster->SetFallingSpeed(TempMonster->GetFallingSpeed() + second);
			if (TempMonster->CanWalk())
				TempMonster->SetCanWalk(false);
		}
		else
		{
			if (TempMonster->GetFallingSpeed() != 1.0f)
				TempMonster->SetFallingSpeed(1.0f);
			if (!TempMonster->CanWalk())
				TempMonster->SetCanWalk(true);
		}
	}
	
	if (Resettimer > -1 && Resettimer <= second)
	{
		player->ResetSprite();
		Resettimer = 1.0f;
	}
	else Resettimer -= second;
	//if (_MoveType.Down && !_MoveType.Up)
	//{
	//	player->PlayerSprite()->setPositionY(player->PlayerSprite()->getPositionY() - 1.0f);
	//	player->DoAction(DOWN);
	//	Resettimer = 1.2f;
	//}
	//if (_MoveType.Up && !_MoveType.Down)
	//{
	//	player->setPositionY(player->getPositionY() + 1.0f);
	//}
	if (_MoveType.Left && !_MoveType.Right && CanMoveLeft(player))
	{
		//setPositionX(getPositionX() + 1.0f);
		player->DoAction(WALK);
		player->setFlipX(false);
		player->SetFacing(Left);
		player->setPositionX(player->getPositionX() - 1.0f);
		Resettimer = 1.0f;
	}
	if (_MoveType.Right && !_MoveType.Left && CanMoveRight(player))
	{
		player->DoAction(WALK);
		player->setFlipX(true);
		player->SetFacing(Right);
		//setPositionX(getPositionX() - 1.0f);
		player->setPositionX(player->getPositionX() + 1.0f);
		Resettimer = 1.0f;
	}
}